package com.attendance.chdingtask.controller;


import com.attendance.chdingtask.config.WebLog;
import com.attendance.chdingtask.model.AuthInfo;
import com.attendance.chdingtask.model.CorpUserDetail;
import com.attendance.chdingtask.service.AuthInfoDaoService;
import com.attendance.chdingtask.utils.common.Result;
import com.taobao.api.ApiException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@Api(value = "auth", description = "免登鉴权接口", consumes = "application/json;charset=UTF-8")
@RequestMapping(value = "/auth")
public class AuthController {

    @Autowired
    private AuthInfoDaoService authHelper;


    @PostMapping("/login")
    @ResponseBody
    @WebLog(description = "免登接口")
    @ApiOperation(value = "免登接口，提交信息包含corpid与aggentId", notes = "{\"corpId\": \"组织id\",\"agentId\": \"agentId\",\"code\": \"应用授权码\"}")
    public Result login(@RequestBody AuthInfo authInfo) {
        CorpUserDetail userDetail;
        try {
            userDetail = authHelper.login(authInfo);
        } catch (ApiException e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
        return Result.success(userDetail);
    }

    @GetMapping("/getJsConfig")
    @ResponseBody
    @WebLog(description = "鉴权接口")
    @ApiOperation(value = "鉴权接口", notes = "{\"corpId\": \"组织id\",\"agentId\": \"agentId\"}")
    public Result getPcJsConfig(HttpServletRequest request) {
        String urlString = request.getHeader("Referer");
        String corpId = request.getParameter("corpId");
        String agentId = request.getParameter("agentId");
        AuthInfo info = authHelper.findByCorpIdAndAppKey(corpId, agentId);
        if (null == info) {
            return Result.error("应用信息未注册，请检查！agentId 为：" + agentId);
        }
        return Result.success(authHelper.getConfig(urlString, info));
    }



    @PostMapping("/register")
    @ResponseBody
    @WebLog(description = "应用注册")
    @ApiOperation(value = "应用注册", notes = "{}")
    public Result sendMessage(@RequestBody AuthInfo info){
        try{
            authHelper.create(info);
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
        return Result.success();
    }

}
